package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
//菜品以及菜品口味的操作
public class DishController {
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> add(@RequestBody DishDto dishDto){
        dishService.addDishAndFlavor(dishDto);
        //延时双删
        String key = "dish_"+dishDto.getCategoryId()+"_2";
        redisTemplate.delete(key);
        return R.success("添加菜品成功！");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize,String name){
        //分页
        Page<Dish> dishPage = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>(page,pageSize);
        //条件
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.like(name != null,Dish::getName,name);

        dishService.page(dishPage,dishLambdaQueryWrapper);

        //拷贝Dish中的属性到DishDto中（忽略records属性）
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        //将dto中的records属性合并和dish一起
        List<Dish> records = dishPage.getRecords();


        /*
        好像可以替换，但是不会
        records.forEach(new Consumer<Dish>() {
            @Override
            public void accept(Dish dish) {
                DishDto dishDto = new DishDto();

                BeanUtils.copyProperties(dish, dishDto);

                //操作每一个菜品对象
                Long categoryId = dish.getCategoryId();
                //根据id查询分类对象
                Category byId = categoryService.getById(categoryId);
                //拿到菜品的分类名称
                String name1 = byId.getName();
                dishDto.setCategoryName(name1);
            }
        });

        */
        List<DishDto> list = records.stream().map((item) -> {

            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> selectById(@PathVariable Long id){
        DishDto dishDto = dishService.selectDishAndFlavorById(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateDishAndFlavor(dishDto);

        //延时双删
        String key = "dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("编辑成功");
    }

    @GetMapping("/list")
    @Cacheable(value = "dishCache",key= "#dish.categoryId+'_'+#dish.status")
    public R<List<DishDto>> list(Dish dish){
        //先看缓存
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //先从redis中获取缓存数据
        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishDtoList != null){
            //缓存有东西，从缓存里拿
            return R.success(dishDtoList);
        }


        //select * from dish where categoryId = 传过来的分类id（分类表）
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //可以只查询正在售卖的菜品，但是感觉没必要

        List<Dish> list = dishService.list(dishLambdaQueryWrapper);

        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            //select * from dish_f**** where dish_id = (前端传过来的菜品id)
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}
